<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { getUrlKey } from '@/utils/getUrlKey'
export default {
  name: 'App',
  data() {
    return {
      tokenid: getUrlKey('tokenid', window.location.href),
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.setToken()
  },
  methods: {
    setToken() {
      this.$store.dispatch('user/setToken', this.tokenid)
      this.$store.dispatch('baseData/getBaseData')
      this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
      this.tokenLogin()
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    tokenLogin() {
      this.$store.dispatch('user/tokenLogin', this.tokenid)
    }
  }
}
</script>
